<?php

/**
 * 二维数组去重
 * @param $array
 * @return array
 */
function remove_duplicate($array)
{
    $result = [];
    foreach ($array as $key => $value) {
        $has = false;
        foreach ($result as $val) {
            if ($val['id'] == $value['id']) {
                $has = true;
                break;
            }
        }
        if (!$has)
            $result[] = $value;
    }

    return $result;
}

/**
 * 获取用户真实iP
 *  */
function getIp()
{
    if (!empty($_SERVER["HTTP_CLIENT_IP"])) {
        $cip = $_SERVER["HTTP_CLIENT_IP"];
    } else if (!empty($_SERVER["HTTP_X_FORWARDED_FOR"])) {
        $cip = $_SERVER["HTTP_X_FORWARDED_FOR"];
    } else if (!empty($_SERVER["REMOTE_ADDR"])) {
        $cip = $_SERVER["REMOTE_ADDR"];
    } else {
        $cip = '';
    }
    preg_match("/[\d\.]{7,15}/", $cip, $cips);
    $cip = isset($cips[0]) ? $cips[0] : 'unknown';
    unset($cips);

    return $cip;
}

function get_client_ip_function()
{
    if (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
        $ip = getenv('HTTP_CLIENT_IP');
    } elseif (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
        $ip = getenv('HTTP_X_FORWARDED_FOR');
    } elseif (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
        $ip = getenv('REMOTE_ADDR');
    } elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }

    return preg_match('/[\d\.]{7,15}/', $ip, $matches) ? $matches [0] : '';
}

function str_rand()
{
    return md5(uniqid(microtime(true), true));
}

//生成订单号
function rand_no()
{
    // 订单流水号前缀
    $prefix = date('YmdHis');
    for ($i = 0; $i < 10; $i++) {
        // 随机生成 6 位的数字
        $no = $prefix . str_pad(random_int(0, 999999), 6, '0', STR_PAD_LEFT);
        // 判断是否已经存在
        if (!\App\Models\Order::where('no', $no)->exists()) {
            return $no;
        }
        usleep(100);
    }
    \Log::warning(sprintf('find order no failed'));

    return false;

}

if (!function_exists('image_url')) {
    /**
     * Get image url.
     *
     * @param $path
     * @param null $driver
     * @return array|string
     */
    function image_url($path, $driver = null)
    {
        if (is_array($path)) {
            $path = array_map(function ($item) {
                return image_url($item);
            }, $path);

            return $path;
        }

        if (!$path) {
            return '';
        }

        $driver = $driver ?: config('filesystems.default');
        // 如果 image 字段本身就已经是完整的 url 就直接返回
        if (\Illuminate\Support\Str::startsWith($path, ['http://', 'https://'])) {
            return $path;
        }
        $disk = \Storage::disk($driver);

        if ($driver === 'qiniu' && env('QINIU_USE_HTTPS')) {
            return $disk->url(['path' => $path, 'domainType' => 'https']);
        } else {
            return $disk->url($path);
        }
    }
}

/**
 * 获取定位
 *
 * @param $address
 * @return bool|string
 */
function getLocation($address)
{
    $ak = env('MAP_AK');

    $url = 'http://api.map.baidu.com/geocoder/v2/?address=' . $address . '&output=json&ak=' . $ak . '&callback=showLocation//GET请求';

    $ch = curl_init();
    // 2. 设置选项，包括URL
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($ch);

    curl_close($ch);

    return json_decode($output);

}

//获取省市区
function getPlaceName($id, $areaType)
{
    if ($areaType == 'district') {
        return \App\Models\SysDistrict::where('id', $id)->value('name');
    }

    if ($areaType == 'city') {
        return \App\Models\SysCity::where('id', $id)->value('name');
    }

    if ($areaType == 'province') {
        return \App\Models\SysProvince::where('id', $id)->value('name');
    }
}

//用户编号
if (!function_exists('user_nu')) {

    function user_nu($length = 7)
    {
        $nu = '';

        for ($i = 1; $i <= $length; $i++) {         //通过循环指定长度
            $rand_code = mt_rand(0, 9);     //指定为数字

            $nu .= $rand_code;
        }

        //检查是否存在
        $flag = \App\Models\User::where('user_nu', $nu)->value('id');

        if ($flag) {
            $nu = user_nu($length);
        }

        return $nu;
    }

}

//获取模型名称
if (!function_exists('getModelName')) {

    function getModelName($model)
    {
        return array_last(explode('\\', $model));
    }

}

//金额保留两位小数
if (!function_exists('getMoneyFormat')) {

    function getMoneyFormat($amount)
    {
        if (!$amount) {
            return '0.00';
        }

        return sprintf("%.2f", $amount);
    }

}

//判断是否是移动端访问
if (!function_exists('isMobile')) {
    function isMobile()
    {
        // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
        if (isset ($_SERVER['HTTP_X_WAP_PROFILE'])) {
            return TRUE;
        }
        // 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
        if (isset ($_SERVER['HTTP_VIA'])) {
            return stristr($_SERVER['HTTP_VIA'], "wap") ? TRUE : FALSE;// 找不到为flase,否则为TRUE
        }
        // 判断手机发送的客户端标志,兼容性有待提高
        if (isset ($_SERVER['HTTP_USER_AGENT'])) {
            $clientkeywords = [
                'mobile', 'nokia', 'sony', 'ericsson', 'mot', 'samsung', 'htc', 'sgh', 'lg', 'sharp', 'sie-', 'philips', 'panasonic',
                'alcatel', 'lenovo', 'iphone', 'ipod', 'blackberry', 'meizu', 'android', 'netfront', 'symbian', 'ucweb',
                'windowsce', 'palm', 'operamini', 'operamobi', 'openwave', 'nexusone', 'cldc', 'midp', 'wap',
            ];
            // 从HTTP_USER_AGENT中查找手机浏览器的关键字
            if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
                return TRUE;
            }
        }
        if (isset ($_SERVER['HTTP_ACCEPT'])) { // 协议法，因为有可能不准确，放到最后判断
            // 如果只支持wml并且不支持html那一定是移动设备
            // 如果支持wml和html但是wml在html之前则是移动设备
            if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== FALSE) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === FALSE || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
                return TRUE;
            }
        }

        return FALSE;
    }
}

if (!function_exists('picturesFormatToButton')) {
    function picturesFormatToButton($pictures)
    {
        if (is_array($pictures)) {
            $pictures = array_map(function ($item) {
                return image_url($item);
            }, $pictures);

            $str = '';

            foreach ($pictures as $item) {
                $str .= '<a target="_blank" href="' . $item . '"><img src="' . $item . '" style="margin-right:5px;width: 20%;"></a>';
            }

        } else {
            $item = image_url($pictures);

            $str = '<a target="_blank" href="' . $item . '"><img src="' . $item . '" style="margin-right:5px;width: 20%;"></a>';
        }

        return $str;
    }
}

